/*
 * @Description: 
 * @Author: zhuhao
 * @Date: 2020-11-12 18:21:53
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2021-04-13 16:45:42
 */
// 配置跨越携带cookie 和证书
import axios from 'axios'
import Cookies from 'js-cookie'
import { Loading } from 'element-ui';
import { Message } from 'element-ui';

axios.defaults.withCredentials = true
axios.defaults.timeout = 50000
window._xvueAxios = axios

// 请求预处理
axios.interceptors.request.use(
    async config => {
        config.headers['XSRF-TOKEN'] = Cookies.get('XSRF-TOKEN')
        config.headers['version-number'] = 'V1R1C00_1';
        //获取token
        try {
          const adoData = await window.ado.parameters('token');
          console.log('token信息 >>> ', adoData);
          if(adoData.code === 1){
            config.headers['gc-authentication'] = adoData.data.token;
          }
        }catch (e) {
          await Promise.reject(e)
        }

        // 判断是否登录或注销
        if (config.url.indexOf('/logout') > -1) {
            let cookeNames = Cookies.get()
            if (cookeNames) {
                for (let i = 0; i < Object.keys(cookeNames).length; i++) {
                    Cookies.remove(cookeNames[i])
                }
            }
            Cookies.remove('XSRF-TOKEN')
            return config
        }
        console.log('请求参数 >>> ', config);
        return config
    },
    err => {
        console.log('请求拦截错误 >>> ', err);
        return Promise.reject(err)
    }
)

let __isRetry__ = false;

axios.interceptors.response.use(
    response => {
        return response;
    },
    error => {
        console.error('响应错误 >>>', error)
        if (error.constructor.name == 'Cancel') {
            return error
        }
        if (axios.isCancel(error)) {
            return new Promise(() => { })
        }
        // accessToken失效
        if (error.response && error.response.status === 401) {
            let config = error.config;
            if (!__isRetry__) {
                window.ado.refreshToken().then(res => {
                    __isRetry__ = true;
                    config.headers['gc-authentication'] = res.data.token;
                    return axios(config)
                })
            } else {
                let msg = error.response.data.msg || error.response.data;
                return Promise.reject(msg);
            }
        }
        if (error.response.status === 403) {

        }
        return Promise.reject(error)
    }
)
